package edu.mapi.aamas.behaviors;

import java.util.Vector;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.messaging.TopicManagementHelper;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import edu.mapi.aamas.common.VehicleState;
import edu.mapi.aamas.common.WorldState;

public class UpdateState extends CyclicBehaviour {

	private WorldState world = new WorldState();

	private boolean initialized = false;
	private MessageTemplate template = null;
	private Vector<StateChangeListener> listeners=new Vector<StateChangeListener>(); 

	public void action() {
		//System.out.println("UpdateState! "+initialized);
		if (!initialized) {
			try {
				TopicManagementHelper topicHelper = (TopicManagementHelper) myAgent.getHelper(TopicManagementHelper.SERVICE_NAME);
				AID stateTopic = topicHelper.createTopic("worldstate");				
				topicHelper.register(stateTopic);
				template = MessageTemplate.MatchTopic(stateTopic);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			initialized = true;
		}
		
		ACLMessage message = myAgent.receive(template);

		if (message != null) {
			try {
				VehicleState state = (VehicleState)message.getContentObject();
				world.putVehicleState(state.getId(), state);
				//warn listener
				for(StateChangeListener list:listeners)
				{
					list.receiveMessage(state);
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		else {
			block();
		}

	}

	public void addStateChange(StateChangeListener StCL)
	{
		listeners.add(StCL);
	}

	public void removeStateChange(StateChangeListener StCL)
	{
		listeners.remove(StCL);
	}

	/**
	 * @return the world
	 */
	public WorldState getWorld() {
		return world;
	}

	/**
	 * @param world the world to set
	 */
	public void setWorld(WorldState world) {
		this.world = world;
	}
}
